#include "utils.h"
#if USE_UTILS
#include "../../board.h"
#include <stdio.h>

#define PMU_BASE_ADDR 0xd4282800

void pmu_write(uint32_t offset, uint32_t val)
{
    writel(val, PMU_BASE_ADDR + offset);
}

uint32_t pmu_read(uint32_t offset)
{
    return (uint32_t)readl(PMU_BASE_ADDR + offset);
}

void pmu_write_bits(uint32_t offset, uint32_t value, uint32_t bits, uint32_t shifts)
{
    uint32_t i = 0;
    uint32_t mask = 0;
    uint32_t reg_val = 0;

    if ((bits + shifts) > 32) {
        printf("%s: %d param (%d, %d) is error!!!! \n", __FUNCTION__, __LINE__, bits, shifts);
        return;
    }

    for (i = 0; i < bits; i++) {
        mask |= (1 << i);
    }

    reg_val = pmu_read(offset);
    reg_val &= ~(mask << shifts);
    reg_val |= (value << shifts);
    pmu_write(offset, reg_val);
}

void pmu_set_bits(uint32_t offset, uint32_t bits)
{
    pmu_write(offset, pmu_read(offset) | bits);
}

void pmu_clear_bits(uint32_t offset, uint32_t bits)
{
    pmu_write(offset, pmu_read(offset) & ~bits);
}

#if USE_CRANE_LCD || USE_CRANE_CAMERA

#define LCD_BASE_ADDR 0xd420a000

void lcdc_write(uint32_t offset, uint32_t val)
{
    writel(val, LCD_BASE_ADDR + offset);
}

uint32_t lcdc_read(uint32_t offset)
{
    return (uint32_t)readl(LCD_BASE_ADDR + offset);
}

void lcdc_write_bits(uint32_t offset, uint32_t value, uint32_t bits, uint32_t shifts)
{
    uint32_t i = 0;
    uint32_t mask = 0;
    uint32_t reg_val = 0;

    if ((bits + shifts) > 32) {
        printf("%s: %d param (%d, %d) is error!!!! \n", __FUNCTION__, __LINE__, bits, shifts);
        return;
    }

    for (i = 0; i < bits; i++) {
        mask |= (1 << i);
    }

    reg_val = lcdc_read(offset);
    reg_val &= ~(mask << shifts);
    reg_val |= (value << shifts);
    lcdc_write(offset, reg_val);
}


void lcdc_set_bits(uint32_t offset, uint32_t bits)
{
    lcdc_write(offset, lcdc_read(offset) | bits);
}

void lcdc_clear_bits(uint32_t offset, uint32_t bits)
{
    lcdc_write(offset, lcdc_read(offset) & ~bits);
}

#define JPEG_BASE_ADDR 0xd420cc00
void jpu_write(uint32_t offset, uint32_t val)
{
    writel(val, JPEG_BASE_ADDR + offset);
}

uint32_t jpu_read(uint32_t offset)
{
    return (uint32_t)readl(JPEG_BASE_ADDR + offset);
}

void jpu_write_bits(uint32_t offset, uint32_t value, uint32_t bits, uint32_t shifts)
{
    uint32_t i = 0;
    uint32_t mask = 0;
    uint32_t reg_val = 0;

    if((bits + shifts) > 32){
        printf("%s: %d param (%d, %d) is error!!!! \n", __FUNCTION__, __LINE__, bits, shifts);
        return;
    }

    for(i = 0; i<bits; i++){
        mask |= (1 << i);
    }

    reg_val = jpu_read(offset);
    reg_val &= ~(mask << shifts);
    reg_val |= (value << shifts);
    jpu_write(offset, reg_val);
}

void jpu_set_bits(uint32_t offset, uint32_t bits)
{
    jpu_write(offset, jpu_read(offset) | bits);
}

void jpu_clear_bits(uint32_t offset, uint32_t bits)
{
    jpu_write(offset, jpu_read(offset) & ~bits);
}

#endif
#endif

